package ynu.edu.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.dto.CartDTO;
import ynu.edu.entities.BaseResponse;
import ynu.edu.entity.CartEntity;
import ynu.edu.exception.ResourceNotFoundException;
import ynu.edu.feign.FoodFeignClient;
import ynu.edu.repository.CartRepository;
import ynu.edu.service.CartService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 购物车服务实现
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private FoodFeignClient foodFeignClient;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 添加商品到购物车
     */
    @Override
    @Transactional
    public CartDTO addToCart(CartEntity cart) {
        // 检查购物车是否已存在该商品
        Optional<CartEntity> existingCart = cartRepository.findByUserIdAndFoodIdAndBusinessId(
                cart.getUserId(), cart.getFoodId(), cart.getBusinessId());

        CartEntity savedCart;
        if (existingCart.isPresent()) {
            // 更新数量
            CartEntity existingCartEntity = existingCart.get();
            existingCartEntity.setQuantity(existingCartEntity.getQuantity() + cart.getQuantity());
            savedCart = cartRepository.save(existingCartEntity);
        } else {
            // 保存新的购物车项
            savedCart = cartRepository.save(cart);
        }

        // 获取食品信息
        return enrichCartWithFoodInfo(savedCart);
    }

    /**
     * 更新购物车商品数量
     */
    @Override
    @Transactional
    public CartDTO updateCartItemQuantity(Integer cartId, Integer quantity) {
        CartEntity cart = cartRepository.findById(cartId)
                .orElseThrow(() -> new ResourceNotFoundException("购物车项", "ID", cartId));

        cart.setQuantity(quantity);
        CartEntity updatedCart = cartRepository.save(cart);

        return enrichCartWithFoodInfo(updatedCart);
    }

    /**
     * 获取用户购物车列表
     */
    @Override
    public List<CartDTO> getCartsByUserId(String userId) {
        List<CartEntity> carts = cartRepository.findByUserId(userId);
        return enrichCartsWithFoodInfo(carts);
    }

    /**
     * 获取用户特定商家的购物车列表
     */
    @Override
    public List<CartDTO> getCartsByUserIdAndBusinessId(String userId, Integer businessId) {
        List<CartEntity> carts = cartRepository.findByUserIdAndBusinessId(userId, businessId);
        return enrichCartsWithFoodInfo(carts);
    }

    /**
     * 删除购物车商品
     */
    @Override
    @Transactional
    public void deleteCart(Integer cartId) {
        cartRepository.findById(cartId)
                .orElseThrow(() -> new ResourceNotFoundException("购物车项", "ID", cartId));
        cartRepository.deleteById(cartId);
    }

    /**
     * 清空用户购物车
     */
    @Override
    @Transactional
    public void clearUserCart(String userId) {
        cartRepository.deleteByUserId(userId);
    }

    /**
     * 清空用户特定商家的购物车
     */
    @Override
    @Transactional
    public void clearUserBusinessCart(String userId, Integer businessId) {
        cartRepository.deleteByUserIdAndBusinessId(userId, businessId);
    }

    /**
     * 为购物车列表添加食品详细信息
     */
    private List<CartDTO> enrichCartsWithFoodInfo(List<CartEntity> carts) {
        List<CartDTO> cartDTOs = new ArrayList<>();
        for (CartEntity cart : carts) {
            cartDTOs.add(enrichCartWithFoodInfo(cart));
        }
        return cartDTOs;
    }

    /**
     * 为单个购物车添加食品详细信息
     */
    private CartDTO enrichCartWithFoodInfo(CartEntity cart) {
        CartDTO cartDTO = new CartDTO();
        
        // 复制基本属性
        cartDTO.setCartId(cart.getCartId());
        cartDTO.setFoodId(cart.getFoodId());
        cartDTO.setBusinessId(cart.getBusinessId());
        cartDTO.setUserId(cart.getUserId());
        cartDTO.setQuantity(cart.getQuantity());
        
        // 获取食品信息
        try {
            BaseResponse<Map<String, Object>> response = foodFeignClient.getFoodById(cart.getFoodId());
            if (response.getCode() == 200 && response.getData() != null) {
                Map<String, Object> foodData = response.getData();
                cartDTO.setFoodName((String) foodData.get("foodName"));
                cartDTO.setFoodExplain((String) foodData.get("foodExplain"));
                cartDTO.setFoodImg((String) foodData.get("foodImg"));
                
                // 处理价格
                Object priceObj = foodData.get("foodPrice");
                if (priceObj instanceof Number) {
                    cartDTO.setFoodPrice(BigDecimal.valueOf(((Number) priceObj).doubleValue()));
                } else if (priceObj instanceof String) {
                    cartDTO.setFoodPrice(new BigDecimal((String) priceObj));
                }
            }
        } catch (Exception e) {
            // 降级处理，设置默认值
            cartDTO.setFoodName("未知商品");
            cartDTO.setFoodExplain("暂无描述");
            cartDTO.setFoodImg("");
            cartDTO.setFoodPrice(BigDecimal.ZERO);
        }
        
        return cartDTO;
    }
} 